﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Demo.Web.Mvvm
{
    public class PageControllerModule : IHttpModule
    {
        /// <summary>
        /// You will need to configure this module in the web.config file of your
        /// web and register it with IIS before being able to use it. For more information
        /// see the following link: http://go.microsoft.com/?linkid=8101007
        /// </summary>

        #region IHttpModule Members

        public void Dispose()
        {
            //clean-up code here.
        }

        public void Init(HttpApplication context)
        {
            context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
        }

        void context_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication)sender;
            Page page = application.Context.CurrentHandler as Page;
            if (page != null)
            {
                page.PreLoad += (src, args) => BuildController(page);
                page.Unload += (src, args) => UnloadController(page);
            }
        }


        public static void BuildController(Page page)
        {
            HttpContext.Current.Trace.Write("PageControllerModule", "Begin BuildController");
            long dt1 = DateTime.Now.Ticks;
            PageControllerBuilder.BuildController(page);
            TimeSpan ts = new TimeSpan(DateTime.Now.Ticks - dt1);
            HttpContext.Current.Trace.Write("PageControllerModule", "End BuildController " + ts.TotalSeconds);

#if(DEBUG)
            HttpContext.Current.Items["__time_PageControllerModule_BuildController"] = ts.TotalSeconds;
#endif

        }

        public static void UnloadController(Page page)
        {
            HttpContext.Current.Trace.Write("PageControllerModule", "Begin UnloadController");
            PageControllerBuilder.UnloadController(page);
            HttpContext.Current.Trace.Write("PageControllerModule", "End UnloadController");
        }

        #endregion
    }
}
